package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	"gozero-demo/internal/config"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/crontab"
	"gozero-demo/internal/handler"
	"gozero-demo/internal/middleware"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/utils"
	"net/http"
)

//var configFile = flag.String("f", "etc/gozero-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	//调用自定义的GetConfigFile方法，读取当前配置的env信息
	configFile := config.GetConfigFile("")
	conf.MustLoad(configFile, &c)

	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	// 使用中间件
	server.Use(middleware.LoggingRequestMiddleware)

	// 使用拦截器
	httpx.SetErrorHandler(func(err error) (int, any) {
		switch e := err.(type) {
		case *utils.MyError:
			return http.StatusOK, utils.Fail(e)
		default:
			return http.StatusOK, utils.ErrorResponse(constants.CodeServerError.Code, err.Error())
		}
	})

	// 定时任务调度
	scheduler, err := crontab.InitScheduler(ctx)
	if err != nil {
		fmt.Printf("Failed to initialize scheduler: %v", err)
	}
	scheduler.Start()

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
